<?php
include '_init_.php';
$DEBUG = isset($_REQUEST['debug'])?TRUE:FALSE;
if ( !isset($_REQUEST['code'])  ||  $_REQUEST['code'] !== 'skdkYewsmqew66x' ) {
	exit();
}
$dtUser = new DataTable(constant('DB_TABLE_MEMBER'));
$user_list = $dtUser->get_list("`status`='active' and `is_subscribe_epaper`='Y'");
$dt = new DataTable(constant('DB_TABLE_EPAPER_SEND_QUEUE'));
$dt_epaper = new DataTable(constant('DB_TABLE_EPAPER_CONTENT'));
$condition = "`status`='wait_send'";
$queue = $dt->get_list($condition);
foreach($queue as $cfg_send)
{
	if ( !$DEBUG ) {
		$epoch = time();
		$set_epoch = strtotime($cfg_send['send_datetime']);
		if ( abs($epoch - $set_epoch) > 3600){
			continue;
		}
	}
	$epaper_row = $dt_epaper->get($cfg_send['epaper_id']);
	$send_email_address = array();
	if ( $epaper_row ) {
		$address_list = explode(',', $cfg_send['email_address']);
		foreach ($address_list as $address){
			if ( in_array($address, $send_email_address)) {
				continue;
			}
			$GLOBALS['APP_INSTANCE']->send_out_email($address,$epaper_row['subject'],html_entity_decode($epaper_row['content']));
			$send_email_address[] = $address;
		}
		//send subscribe users
		foreach($user_list as $user_data){
			$address = $user_data['email'];
			if ( in_array($address, $send_email_address)) {
				continue;
			}
			$GLOBALS['APP_INSTANCE']->send_out_email($address,$epaper_row['subject'],html_entity_decode($epaper_row['content']));
			$send_email_address[] = $address;
		}
	}
	$update_data = array('id'=>$cfg_send['id'],'status'=>'sent');
	$dt->save($update_data);
}
?>